<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/4/25
 * Time: 11:05
 */

namespace app\common\service\environmentAnalysis;

use think\Db;
use think\facade\Config;
use app\common\service\CommonService;
use app\common\service\airquality\AirQualityStationAqiRealtimeDayService;

class EnvironmentAnalysisContributeService
{
    /**
     * 获取全要素-贡献度分析左上侧table数据（目前只有电力、焦化、钢铁、水泥）(除了贡献度，表格其他参数和站点选择无关)
     * 减排量暂时为'-' (前台脱硫脱硝选择影响运行浓度、运行效率、减排量，污染物选择和减排前贡献度)
     * 其他各字段都是求和的平均值
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author yy by 2019/4/25
     */
    public function getTableIndustry($param = [])
    {
        $commonService      = new CommonService();
        $industry_limit_arr = $commonService->getIndustryLimitIdmysql();
        if (strtolower($param['company_pollutant_name']) == 'so2') {
            $param['is_sulfur']      = 1;
            $simulate_pollutant      = 'emissions_so2_total';
            $operation_concentration = 'operation_concentration_so2';
            $operating_efficiency    = 'operating_efficiency_so2';
        } else {
            $param['is_sulfur']      = 0;
            $simulate_pollutant      = 'emissions_nox_total';
            $operation_concentration = 'operation_concentration_nox';
            $operating_efficiency    = 'operating_efficiency_nox';
        }
        $list                = [];
        $realCompanyEmission = $commonService->getRealCompanyEmission($param);//实时行业企业多天排放量
        $companyIdArr        = $commonService->getCompanyIdArr(1);
        $dayService          = new AirQualityStationAqiRealtimeDayService();
        $days                = $dayService->diffDays($param['start_time'], $param['end_time']);
        # 按行业
        # 污染物选择判断 影响减排前贡献度
        # 获取查询日期区间相差的天数
        # 查询运行浓度、运行效率、排放量(20190530改为sum)
        # 模拟表(排除掉晋能长治热电有限公司)（不用判断时间）
        $data_simulate = Db::query("select sum($simulate_pollutant * $days) as emissions, industry_id, industry_name
                                from company_industry_monitor_simulation_day_avg
                                where company_id in $companyIdArr and industry_id in $industry_limit_arr
                                group by industry_id"); // 模拟行业多天排放量
        foreach ($data_simulate as $k1 => $v1) {
            $list[$v1['industry_id']]['industry_id']   = $v1['industry_id'];
            $list[$v1['industry_id']]['industry_name'] = $v1['industry_name'];
            # 减排量暂时为'-';
            $list[$v1['industry_id']]['emissions_reduce'] = '-';
            // 目前除了电力行业需要两个表，其他行业只有模拟表的数据
            $list[$v1['industry_id']]['emissions'] = $v1['emissions'];
            if (count($realCompanyEmission) > 0) {
                foreach ($realCompanyEmission as $k2 => $v2) {
                    if ($v2['industry_id'] == $v1['industry_id']) { //模拟表和脱硫脱硝表重复的只有电力（晋能热电）这个行业
                        $list[$v1['industry_id']]['emissions'] = $v2['emissions'] + $v1['emissions'];  //电力行业的排放量
                    }
                }
            }
        }
        // 计算各行业多天的运行浓度、运行效率
        // 1.分子为行业多天排放量的和
        // 2.分母为 ∑(每家企业多天排放量的和/每家企业多天的运行浓度) ---行业运行浓度的分母
        // 3.分母为 ∑(每家企业多天排放量的和/（1 - 每家企业多天的运行效率)）---行业运行效率的分母
        $param['industry_id']  = 1;
        $real_concentration    = $commonService->getRealConcentration($param, 1); //实时企业多天的运行浓度
        $real_efficiency       = $commonService->getRealEfficiency($param, 1); //实时企业多天的运行效率
        $real_denominator      = $realCompanyEmission[0]['emissions'] / $real_concentration[0]['concentration'];
        $data_simulate_company = Db::query("select sum($simulate_pollutant * $days) / avg($operation_concentration) as result_concentration,sum($simulate_pollutant * $days) / (1-avg($operating_efficiency)) as result_efficiency, industry_id, company_id, company_name
                                from company_industry_monitor_simulation_day_avg
                                where company_id in $companyIdArr and industry_id in $industry_limit_arr
                                group by industry_id, company_id"); // 模拟行业企业多天排放量
        $arr                   = [];
        foreach ($data_simulate_company as $kds => $vds) {
            $arr[$vds['industry_id']]['concentration'][] = $vds['result_concentration'];
            $arr[$vds['industry_id']]['efficiency'][]    = $vds['result_efficiency'];
        }
        foreach ($arr as $karr => &$varr) {
            if ($karr == 1) {
                $varr['concentration'] = array_sum($varr['concentration']) + $real_denominator; // 电力行业需要实时企业和模拟企业的分母相加
                $varr['efficiency']    = array_sum($varr['efficiency']) + $real_efficiency[0]['efficiency']; // 电力行业需要实时企业和模拟企业的分母相加
            } else {
                $varr['concentration'] = array_sum($varr['concentration']);
                $varr['efficiency']    = array_sum($varr['efficiency']);
            }
        }
        foreach ($list as $kcon => &$vcon) {
            $vcon['operation_concentration'] = $vcon['emissions'] / $arr[$kcon]['concentration'];
            $vcon['operating_efficiency']    = 1 - $vcon['emissions'] / $arr[$kcon]['efficiency'];
        }

        # 根据前端要求第一个行业增加默认选中
        if (count($list) > 0) {
            $list                   = array_values($list);
            $list[0]['LAY_CHECKED'] = true;
        }
        # 减排前贡献度（不分脱硫脱硝，受污染物选择的影响）(publish_time 等于 predict_time) 如电力行业
        $newTime            = $commonService->getMongoTime($param);
        $companyIdArr       = $commonService->getCompanyIdArr(0);
        $isIndustryId       = $commonService->getIndustryLimitId();
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'industry_id'       => ['$in' => $isIndustryId],
                        'company_id'        => ['$in' => $companyIdArr],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['contribute_pollutant_name']),
                        'predict_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'   => ['industry_id' => '$industry_id', 'company_id' => '$company_id'],
                        'total' => ['$sum' => '$contribution_degree'] //不同行业下不同企业的时间区间贡献值和sum
                    ]
                ],
            ],
//            '$filter'      => [
//                '$where' => "this.publish_time == this.predict_time", //已和数据处理人员协调修改时分秒为 00:00:00
//            ],
//            '$options' => [
//                'projection' => [ 'publish_time'=>1]
//            ],
//            '$publish_time'=> 1,
            'allowDiskUse' => true,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']); //因为要求计算区间平均减排前贡献度
        $arr                = [];
        if ($num > 0) {
            # 指定污染物的时间区间有效浓度和
            $param['pollutant_name'] = str_replace('.', '', strtolower($param['contribute_pollutant_name']));
            $concentration_sum       = $commonService->getConcentration($param);

            # 不同行业不同企业时间区间内的贡献值和
            foreach ($contribution_trend[0]['result'] as $km => $vm) {
                $arr[$vm['_id']['industry_id']][$vm['_id']['company_id']][] = $vm['total'];
            }
            # 不同行业不同企业时间区间内的贡献度
            foreach ($arr as $kn => &$vn) {
                foreach ($vn as $kx => &$vx) {
                    $vx = $concentration_sum > 0 ? $vx[0] / $concentration_sum : '';
                }
                # 因为区间浓度和相同 因此指定行业的区间贡献度等于该行业下所有企业的贡献度和
                $vn = array_sum($vn);
            }
        }
        foreach ($list as $km => &$vm) {
            $vm['contribution_value'] = '-';
            foreach ($arr as $ks => $vs) {
//                ($ks === $vm['industry_id']) ? ($vm['contribution_value'] = $commonService->handleMathNum($vs * 100) . '%') : ''; // 贡献度
                ($ks === $vm['industry_id']) ? ($vm['contribution_value'] = $commonService->contributionRound($vs) . '%') : ''; // 贡献度
            }
        }
        # 排放量单位转化为吨
        $commonService = new CommonService();
        $list          = $commonService->getRealData($list, 'emissions');
        for ($i = 0; $i < count($list); $i++) {
            $list[$i]['operating_efficiency']    = round($list[$i]['operating_efficiency'] * 100, 1) . ' %'; //运行效率
            $list[$i]['operation_concentration'] = round($list[$i]['operation_concentration'], 1) . ' mg/m³'; //运行浓度
            $list[$i]['emissions']               = $list[$i]['emissions'] > 0 ? $list[$i]['emissions'] . ' t' : $list[$i]['emissions']; //排量
        }
        return $list;
    }

    /**
     * 获取指定行业(或者全部行业)下的企业table(默认电力行业)(除了贡献度，表格其他参数和站点选择无关)
     * @author yy by 2019/4/30
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getTableCompany($param = [])
    {
        $result             = [];
        $commonService      = new CommonService();
        $companyIdArr       = $commonService->getCompanyIdArr(1);
        $industry_limit_arr = $commonService->getIndustryLimitIdmysql();
        # 脱硫脱硝判断 影响运行浓度、运行效率、排放量
        if (strtolower($param['company_pollutant_name']) == 'so2') {
            $table                   = 'company_industry_monitor_sulfur_day';
            $emissions               = 'emissions_so2_total';
            $operation_concentration = 'operation_concentration_so2';
            $operating_efficiency    = 'operating_efficiency_so2';
            $param['is_sulfur']      = 1;
        } elseif (strtolower($param['company_pollutant_name']) == 'nox') {
            $table                   = 'company_industry_monitor_nitre_day';
            $emissions               = 'emissions_nox_total';
            $operation_concentration = 'operation_concentration_nox';
            $operating_efficiency    = 'operating_efficiency_nox';
            $param['is_sulfur']      = 0;
        }
        $concentration = $commonService->getRealConcentration($param, 0);        // 所有行业下企业的运行浓度
        $efficiency    = $commonService->getRealEfficiency($param, 0);        // 所有行业下企业的运行效率
        $real_emission = $commonService->getRealCompanyEmission($param, 1);         // 实时企业多天的排放量
        $dayService    = new AirQualityStationAqiRealtimeDayService();
        $days          = $dayService->diffDays($param['start_time'], $param['end_time']);
        # 查询运行浓度、运行效率、排放量(20190530改为求和)
        if ($param['industry_id'] == 'all') {
            # 模拟表(排除掉晋能长治热电有限公司)（不用判断时间）
            $data_simulate = Db::query("select avg($operation_concentration) as operation_concentration, avg($operating_efficiency) as operating_efficiency, sum($emissions * $days) as emissions, company_id, company_name
                                from company_industry_monitor_simulation_day_avg
                                where company_id in $companyIdArr and industry_id in $industry_limit_arr
                                group by company_id");
        } else {
            # 模拟表(排除掉晋能长治热电有限公司)
            $data_simulate = Db::query("select avg($operation_concentration) as operation_concentration, avg($operating_efficiency) as operating_efficiency, sum($emissions * $days) as emissions, company_id, company_name
                                from company_industry_monitor_simulation_day_avg
                                where company_id in $companyIdArr and industry_id = ?
                                group by company_id", [$param['industry_id']]);
        }
        $new_concentration = array_column($concentration, null, 'company_id');
        $new_efficiency    = array_column($efficiency, null, 'company_id');
        $new_emission      = array_column(array_merge($real_emission, $data_simulate), null, 'company_id');
        $list              = [];
        foreach ($new_concentration as $k => $v) {
            $list[$k]['company_id']              = $k;
            $list[$k]['emissions']               = $new_emission[$k]['emissions'];
            $list[$k]['company_name']            = isset($new_emission[$k]['company_name']) ? $new_emission[$k]['company_name'] : '';
            $list[$k]['operating_efficiency']    = $new_efficiency[$k]['efficiency'];
            $list[$k]['operation_concentration'] = $new_concentration[$k]['concentration'];
        }
        $list = array_values($list);
        # 减排前贡献度（不分脱硫脱硝，受污染物选择的影响）
        # 判断是查询所有行业还是指定行业
        if ($param['industry_id'] == 'all') {
            $isIndustryId      = $commonService->getIndustryLimitId();
            $industry_id_where = ['$in' => $isIndustryId];
        } else {
            $industry_id_where = (int)$param['industry_id'];
        }
        $newTime            = $commonService->getMongoTime($param);
        $companyIdArr       = $commonService->getCompanyIdArr(0);
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'industry_id'       => $industry_id_where,
                        'company_id'        => ['$in' => $companyIdArr],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['contribute_pollutant_name']),
                        'publish_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'   => ['company_id' => '$company_id'],
                        'total' => ['$sum' => '$contribution_degree'] //企业贡献值的和
                    ]
                ],
                [
                    '$sort' => [
                        '_id' => -1,
                    ]
                ]
            ],
//            '$filter'      => [
//                '$where' => "this.publish_time == this.predict_time",
//            ],
            'allowDiskUse' => true,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']);
        $con                = [];
        if ($num > 0) {
            # 指定污染物的时间区间有效浓度和
            $param['pollutant_name'] = str_replace('.', '', strtolower($param['contribute_pollutant_name']));
            $concentration_sum       = $commonService->getConcentration($param);
            foreach ($contribution_trend[0]['result'] as $k => $v) {
//                $con[$v['_id']['company_id']] = $concentration_sum > 0 ? $commonService->handleMathNum($v['total'] / $concentration_sum * 100) . '%' : ''; //返给前端是直接就是百分比
                $con[$v['_id']['company_id']] = $concentration_sum > 0 ? $commonService->contributionRound($v['total'] / $concentration_sum) : ''; //返给前端是直接就是百分比
            }
        }
        foreach ($list as $k2 => &$v2) {
            # 减排量暂时为'-'
            $v2['emissions_reduce'] = '-';
            # 贡献度
            $v2['contribution_value'] = '-';
            foreach ($con as $k3 => $v3) {
                ($k3 == $v2['company_id']) ? ($v2['contribution_value'] = $v3) : '';
            }
        }
        # 获取公司简称
        $company = Db::query("select id,short_name,name from basic_company order by id asc");
        $company = array_column($company, null, 'id');
        for ($i = 0; $i < count($list); $i++) {
            $list[$i]['company_name']            = $company[$list[$i]['company_id']]['short_name'] ?: $company[$list[$i]['company_id']]['name'];
            $list[$i]['operating_efficiency']    = round($list[$i]['operating_efficiency'] * 100, 1); //运行效率
            $list[$i]['operation_concentration'] = round($list[$i]['operation_concentration'], 1); //运行浓度
        }
        # 根据某个值高低进行排序
        $rule = array_column($list, 'operation_concentration');//运行浓度
        array_multisort($rule, SORT_DESC, $list);
        $arr['operation_concentration']['date']    = array_column($list, 'company_name');
        $arr['operation_concentration']['data'][0] = array_column($list, 'operation_concentration');
        $arr['operation_concentration']['id']      = array_column($list, 'company_id');

        $rule = array_column($list, 'operating_efficiency');//运行效率
        array_multisort($rule, SORT_DESC, $list);
        $arr['operating_efficiency']['date']    = array_column($list, 'company_name');
        $arr['operating_efficiency']['data'][0] = array_column($list, 'operating_efficiency');
        $arr['operating_efficiency']['id']      = array_column($list, 'company_id');

        $rule = array_column($list, 'emissions');//排放量
        array_multisort($rule, SORT_DESC, $list);
        $arr['emissions']['date']    = array_column($list, 'company_name');
        $arr['emissions']['data'][0] = array_column($list, 'emissions');
        $arr['emissions']['id']      = array_column($list, 'company_id');

        $rule = array_column($list, 'emissions_reduce');//减排量
        array_multisort($rule, SORT_DESC, $list);
        $arr['emissions_reduce']['date']    = array_column($list, 'company_name');
        $arr['emissions_reduce']['data'][0] = array_column($list, 'emissions_reduce');
        $arr['emissions_reduce']['id']      = array_column($list, 'company_id');

        $rule_before = array_column($list, 'company_id');
        $rule        = array_column($list, 'contribution_value');//减排前贡献度
        array_multisort($rule, SORT_DESC, $rule_before, SORT_ASC, $list);
        $arr['contribution_value']['date']    = array_column($list, 'company_name');
        $arr['contribution_value']['data'][0] = array_column($list, 'contribution_value');
        $arr['contribution_value']['id']      = array_column($list, 'company_id');
        # 前台贡献度echart柱状图表不要百分号
        if (count($arr['contribution_value']['data'][0]) > 0) {
            foreach ($arr['contribution_value']['data'][0] as $k4 => &$v4) {
                strstr($v4, '%') ? ($v4 = str_replace('%', '', $v4)) : '';//echart图不要百分号
            }
        }
        # 前台运行效率echart柱状图表不要百分号
        if (count($arr['operating_efficiency']['data'][0]) > 0) {
            foreach ($arr['operating_efficiency']['data'][0] as $k4 => &$v4) {
                strstr($v4, '%') ? ($v4 = str_replace('%', '', $v4)) : '';//echart图不要百分号
            }
        }
        # 排放量单位转化为吨
        $commonService  = new CommonService();
        $result['list'] = $commonService->getRealData($list, 'emissions'); //table数据
        for ($i = 0; $i < count($result['list']); $i++) {
            $result['list'][$i]['operating_efficiency']    = $result['list'][$i]['operating_efficiency'] . ' %'; //运行效率
            $result['list'][$i]['operation_concentration'] = $result['list'][$i]['operation_concentration'] . ' mg/m³'; //运行浓度
            $result['list'][$i]['emissions']               = $result['list'][$i]['emissions'] > 0 ? $result['list'][$i]['emissions'] . ' t' : $result['list'][$i]['emissions']; //排量
            $result['list'][$i]['contribution_value']      = $result['list'][$i]['contribution_value'] . ' %'; //运行效率
        }
        $arr['emissions']['data'][0] = $commonService->getRealData($arr['emissions']['data'][0]);//柱状图
        $result['arr']               = $arr; //柱状图
        return $result;
    }

    /**
     * 空气质量趋势图（今天之前查询发布时间和预报时间，今天及之后查询查询发布时间）
     * @author yy by 2019/5/6
     * @param array $param
     * @return array
     */
    public function getAqiTrend($param = [])
    {
        $list         = [];
        $arr_forecast = [];
        $arr_realtime = [];
        # 预报值趋势图(全要素模块时间选取只能为历史到现在)
        $forecast = Db::query("select aqi, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                    from air_quality_station_aqi_forecast_day
                                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ? and publish_time = predict_time",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);
        # 实际值趋势图((全要素模块时间选取只能为历史到现在)
        $realtime      = Db::query("select aqi, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                    from air_quality_station_aqi_realtime_day
                                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ? ",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);
        $commonService = new CommonService();
        $date_all      = $commonService->getDate($param['start_time'], $param['end_time']);
        # 比较差集(预报值)
        if (count($forecast) > 0) {
            $arr_forecast['date'] = array_column($forecast, 'date');
            $arr_forecast['aqi']  = array_column($forecast, 'aqi');
            $different            = array_values(array_diff($date_all, $arr_forecast['date']));
            $different_num        = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $arr_forecast['date'][] = $different[$i];
                    $arr_forecast['aqi'][]  = '';
                }
            }
            foreach ($arr_forecast['aqi'] as $k => &$v) {
                $v > 0 ? ($v = ceil($v)) : ($v = '');
            }
        } else {
            $arr_forecast['date'] = $date_all;
            for ($i = 0; $i < count($date_all); $i++) {
                $arr_forecast['aqi'][$i] = '';
            }
        }
        # 比较差集(实测值)
        if (count($realtime) > 0) {
            $arr_realtime['date'] = array_column($realtime, 'date');
            $arr_realtime['aqi']  = array_column($realtime, 'aqi');
            $different            = array_values(array_diff($date_all, $arr_realtime['date']));
            $different_num        = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $arr_realtime['date'][] = $different[$i];
                    $arr_realtime['aqi'][]  = '';
                }
            }
            foreach ($arr_realtime['aqi'] as $k2 => &$v2) {
                $v2 > 0 ? ($v2 = ceil($v2)) : ($v2 = '');
            }
        } else {
            $arr_realtime['date'] = $date_all;
            for ($i = 0; $i < count($date_all); $i++) {
                $arr_realtime['aqi'][$i] = '';
            }
        }
        # 依据日期排序
        array_multisort($arr_forecast['date'], $arr_forecast['aqi']);
        array_multisort($arr_realtime['date'], $arr_realtime['aqi']);
        $list['date'] = $date_all;
        for ($i = 0; $i < count($date_all); $i++) {
            $list['date'][$i] = date('m/d', strtotime($list['date'][$i]));
        }
        $list['data'][0] = $arr_forecast['aqi']; //预报值
        $list['data'][1] = $arr_realtime['aqi']; //实测值
        return $list;
    }

    /**
     * 获取工业贡献度趋势
     * @author yy by 2019/5/14
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getIsIndustryTrend($param = [])
    {
        $list               = [];
        $commonService      = new CommonService();
        $isIndustryId       = $commonService->getIndustryLimitId();
        $companyIdArr       = $commonService->getCompanyIdArr(0);
        $newTime            = $commonService->getMongoTime($param);
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1, //贡献值
                        'concentration'       => 1,
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'industry_id'       => ['$in' => $isIndustryId],
                        'company_id'        => ['$in' => $companyIdArr],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['contribute_pollutant_name']),
                        'publish_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'               => '$publish_time',
                        'total'             => ['$sum' => '$contribution_degree'], // 工业单天的贡献值等于工业下各企业的贡献值和
                        'concentration_sum' => ['$avg' => '$concentration']

                    ]
                ],
                [
                    '$sort' => [
                        '_id' => 1,
                    ]
                ]
            ],
            'allowDiskUse' => false,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $commonService      = new CommonService();
        $date_all           = $commonService->getDate($param['start_time'], $param['end_time']);
        $num                = count($contribution_trend[0]['result']);
        if ($num > 0) {
            # 指定污染物的时间区间有效浓度和
            $param['pollutant_name'] = str_replace('.', '', strtolower($param['contribute_pollutant_name']));
            for ($i = 0; $i < $num; $i++) {
                $list['date'][$i] = $list['date'][$i] = date('Y-m-d', strtotime($contribution_trend[0]['result'][$i]['_id']));
//                $list['data'][0][$i] = $contribution_trend[0]['result'][$i]['concentration_sum'] > 0 ? $contribution_trend[0]['result'][$i]['total'] / $contribution_trend[0]['result'][$i]['concentration_sum'] : '';
                $list['data'][0][$i] = $contribution_trend[0]['result'][$i]['concentration_sum'] > 0 ? $commonService->contributionRound($contribution_trend[0]['result'][$i]['total'] / $contribution_trend[0]['result'][$i]['concentration_sum']) : '';
            }
            # 比较差集
            $different     = array_values(array_diff($date_all, $list['date']));
            $different_num = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $list['date'][]    = $different[$i];
                    $list['data'][0][] = '';
                }
            }
        } else {
            $list['date'] = $date_all;
            for ($i = 0; $i < count($list['date']); $i++) {
                $list['data'][0][$i] = '';
            }
        }
        # 依据publish_time排序
        array_multisort($list['date'], $list['data'][0]);
        for ($m = 0; $m < count($list['date']); $m++) {
            $list['date'][$m] = date('m/d', strtotime($list['date'][$m]));
//            $list['data'][0][$m] = ($list['data'][0][$m] > 0) ? $list['data'][0][$m] * 100 : $list['data'][0][$m];//返给前端直接是百分比
            $list['data'][0][$m] = ($list['data'][0][$m] > 0) ? $list['data'][0][$m] : $list['data'][0][$m];//返给前端直接是百分比
        }
        return $list;
    }

    /**
     * 行业贡献度趋势图
     * @author yy by 2019/5/14
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getIndustryTrend($param = [])
    {
        $list               = [];
        $commonService      = new CommonService();
        $isIndustryId       = $commonService->getIndustryLimitId();
        $companyIdArr       = $commonService->getCompanyIdArr(0);
        $newTime            = $commonService->getMongoTime($param);
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1, //贡献度
                        'contribution_degree' => 1,//贡献值
                        'concentration'       => 1,
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'industry_id'       => ['$in' => $isIndustryId],
                        'company_id'        => ['$in' => $companyIdArr],
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['contribute_pollutant_name']),
                        'predict_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'               => ['publish_time' => '$publish_time', 'industry_id' => '$industry_id'],
                        'total'             => ['$sum' => '$contribution_degree'], //因为同一区域同一站点同一行业同一污染物同一天(不同企业)的数据存在多条,此处贡献值为每天的多个公司的和 20190619算法
                        'concentration_sum' => ['$avg' => '$concentration'],//mongodb表此字段已经是浓度和，因此此处求平均值即为这一天的该污染物的浓度和
                    ]
                ],
                [
                    '$sort' => [
                        "_id" => 1,
                    ]
                ]
            ],
            'allowDiskUse' => false,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']);
        # 钢铁焦化电力(水泥玻璃)id(水泥玻璃行业在一起20190611)
        $list['date'] = $commonService->getDate($param['start_time'], $param['end_time']);
        if ($num > 0) {
            foreach ($contribution_trend[0]['result'] as $k => $v) {
                foreach ($isIndustryId as $k2 => &$v2) {
                    if ($v2 === $v['_id']['industry_id']) {
                        $list['data'][$v2][] = [
                            'publish_time'       => date('Y-m-d', strtotime($v['_id']['publish_time'])),
//                            'contribution_value' => $v['concentration_sum'] > 0 ? $v['total'] / $v['concentration_sum'] * 100 : '',
                            'contribution_value' => $v['concentration_sum'] > 0 ? $commonService->contributionRound($v['total'] / $v['concentration_sum']) : '',
                        ];
                    }
                }
            }
            foreach ($list['data'] as $k4 => &$v4) {
                $publish_time_arr = array_column($v4, 'publish_time');
                # 比较差集
                $different = array_values(array_diff($list['date'], $publish_time_arr));
                for ($i = 0; $i < count($different); $i++) {
                    $v4[] = ['publish_time' => $different[$i], 'contribution_value' => ''];
                }
                # 依据publish_time排序
                $sort = array_column($v4, 'publish_time');
                array_multisort($sort, SORT_ASC, $v4);
                $v4 = array_column($v4, 'contribution_value');
            }
            foreach ($list['date'] as $k6 => &$v6) {
                $v6 = date('m/d', strtotime($v6));
            }
        } else {
            for ($i = 0; $i < count($list['date']); $i++) {
                $list['date'][$i] = date('m/d', strtotime($list['date'][$i]));
                foreach ($isIndustryId as $k => $v) {
                    $list['data'][$v][$i] = ''; //各个行业的单天贡献度都为'';
                }
            }
        }
        $list['data'] = array_values($list['data']);
        return $list;
    }

    /**
     * 企业贡献度趋势图(有指定行业和全部行业两种情况)
     * @author yy by 2019/5/15
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyTrend($param = [])
    {
        # 判断是否是全部行业（目前是钢铁电力水泥焦化）
        $list               = [];
        $arr                = [];
        $commonService      = new CommonService();
        $isIndustryId       = $commonService->getIndustryLimitId();
        $newTime            = $commonService->getMongoTime($param);
        $industry_id_arr    = $param['industry_id'] ? (int)$param['industry_id'] : ['$in' => $isIndustryId];
        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document           = [
            'aggregate'    => Config::get('contribution_table_name'),
            'pipeline'     => [
                [
                    '$project' => [
                        'predict_time'        => 1,
                        'publish_time'        => 1,
                        'contribution_name'   => 1,
                        'company_id'          => 1,
                        'industry_id'         => 1,
                        'station_id'          => 1,
                        'region_id'           => 1,
                        'contribution_value'  => 1,//贡献度
                        'contribution_degree' => 1,//贡献值
                        'concentration'       => 1,
                        'difference'          => ['$eq' => ['$publish_time', '$predict_time']]
                    ],
                ],
                [
                    '$match' => [
                        'difference'        => true,
                        'company_id'        => (int)$param['company_id'],
                        'industry_id'       => $industry_id_arr,
                        'region_id'         => (int)$param['region_id'],
                        'station_id'        => (int)$param['station_id'],
                        'contribution_name' => strtoupper($param['contribute_pollutant_name']),
                        'predict_time'      => [
                            '$gte' => $newTime['start_time'],
                            '$lte' => $newTime['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'               => '$publish_time',
                        'total'             => ['$sum' => '$contribution_degree'], // 同一企业可能对应多个行业，贡献值求和 TODO
                        'concentration_sum' => ['$avg' => '$concentration'] // 以时间分组的浓度和求平均 等于 同一天该站点的浓度
                    ]
                ],
                [
                    '$sort' => [
                        "_id" => 1,
                    ]
                ]
            ],
            'allowDiskUse' => false,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $commonService      = new CommonService();
        $list['date']       = $commonService->getDate($param['start_time'], $param['end_time']);
        $num                = count($contribution_trend[0]['result']);
        if ($num > 0) {
            foreach ($contribution_trend[0]['result'] as $k3 => &$v3) {
                $v3['_id'] = date('Y-m-d', strtotime($v3['_id']));
//                $arr['data'][0][] = $v3['concentration_sum'] > 0 ? $v3['total'] / $v3['concentration_sum'] : '';
                $arr['data'][0][] = $v3['concentration_sum'] > 0 ? $commonService->contributionRound($v3['total'] / $v3['concentration_sum']) : '';
            }
            $arr['date'] = array_column($contribution_trend[0]['result'], '_id');
            # 比较差集
            $different     = array_values(array_diff($list['date'], $arr['date']));
            $different_num = count($different);
            if ($different_num > 0) {
                for ($i = 0; $i < $different_num; $i++) {
                    $arr['date'][]    = $different[$i];
                    $arr['data'][0][] = '';
                }
            }
        } else {
            $arr['date'] = $list['date'];
            for ($i = 0; $i < count($arr['date']); $i++) {
                $arr['data'][0][$i] = '';
            }
        }
        # 依据publish_time排序
        array_multisort($arr['date'], $arr['data'][0]);
        for ($m = 0; $m < count($arr['date']); $m++) {
            $arr['date'][$m] = date('m/d', strtotime($arr['date'][$m]));
//            $arr['data'][0][$m] = ($arr['data'][0][$m] === '') ? '' : $arr['data'][0][$m] * 100;//返回给前端直接就是百分比
            $arr['data'][0][$m] = ($arr['data'][0][$m] === '') ? '' : $arr['data'][0][$m];//返回给前端直接就是百分比
        }
        return $arr;
    }
}